package com.tueye.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tueye.base.util.Page;
import com.tueye.dao.IArticleDao;
import com.tueye.entity.ArticleTopic;
import com.tueye.entity.TopicType;
import com.tueye.service.IArticleService;
import com.tueye.service.ITopicService;
import com.tueye.utils.DateUtils;
import com.tueye.utils.UUIDGenerator;

/**
 * 用户添加控制层操作demo
 * spring mvc 2.5 支持MultiActionController
 * @author hanxiaowei
 * modify by yuyue 20091224
 * 增加一个通过topicID查出所有专题内容的方法
 * 
 */
@SuppressWarnings("unchecked")
@org.springframework.stereotype.Controller
@RequestMapping("/article.do")
public class ArticleController extends BaseController {
	private Log log = LogFactory.getLog(ArticleController.class);
	@Autowired
	@Qualifier("articleService")
	private IArticleService articleService;
	
	@Autowired
	@Qualifier("topicService")
	private ITopicService topicService;
	
	@Autowired
	@Qualifier("articleDao")
	protected IArticleDao articleDao;
	//@RequestMapping(method = { RequestMethod.POST })
	@RequestMapping(params = "action=PageShow")
	public String PageShow (HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		// js传过来的参数列表：
		// page:页数
		// rp:每页显示多少条
		// sortname：排序的字段名称
		// sortorder: 排序的方向；比如：asc，desc；
		// query : 查询的条件
		// qtype ：查询的类型
		
		String rp=request.getParameter("rp"); //每页显示的数据数
		String pageString=request.getParameter("page");//获取 flexgrid传过来的页数。
		String query=request.getParameter("query");//获取 查询的条件
		if(null != query) {
			query = java.net.URLDecoder.decode(query , "UTF-8");//解码
		}
		String error = request.getParameter("ss");
		//error.indexOf("23");
		String qtype=request.getParameter("qtype");//获取 查询的类型
		String sortorder=request.getParameter("sortorder");//获取 查询的类型
		if(pageString == null || pageString.length() == 0) {
			pageString = "1";
		}
		StringBuffer hql = new StringBuffer(" from com.tueye.entity.ArticleTopic ");
		//if(StringUtils.isNotEmpty(query)) hql.append(" where "+query);
		if(StringUtils.isNotEmpty(query)) {
			hql.append(" where "+qtype+" ='"+query+"'");
		}
		if(StringUtils.isNotEmpty(qtype)) {
			hql.append("   order   by "+qtype);
		}
		if(StringUtils.isNotEmpty(sortorder)) {
			hql.append("   "+sortorder);
		}
		System.out.println("sql"+hql);
		Page pageModel = articleService.pagedQueryByHQL(hql.toString(), Integer.valueOf(pageString), Integer.valueOf(rp), null);
		
		Map pageInfo = new HashMap();
		pageInfo.put("page", new Integer(pageString));
		pageInfo.put("total", pageModel.getTotalCount());
		//生成json字符串
//		if(pageModel.getResult() instanceof ArrayList){
//			System.out.println("*******"+pageModel.getResult());
//			
//		}
		String jsonStr = getJsonString((ArrayList)pageModel.getResult(),pageInfo);
		
		response.setContentType("html/txt");
		response.setCharacterEncoding("utf-8");
		response.getWriter().println(jsonStr);
		
/*		response.setContentType("html/txt");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		response.setHeader("Pragma", "no-cache");
		response.getWriter().write(jsonStr);
		response.getWriter().flush();
		response.getWriter().close();*/
		
		return null;
	}
	
	@RequestMapping(params = "action=toAdd")
	public String toAdd(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		TopicType type = new TopicType();
		//添加
		String hql = "from TopicType where pid is null";
		List list = articleDao.getArticleByHql(hql);
	    request.setAttribute("list", list);
	    return "/pages/admin/article/addArticle";
	}
	
	@RequestMapping(params = "action=edit")
	public String edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		String mainId = request.getParameter("id");
	    ArticleTopic article = new ArticleTopic();
		//添加
	    article = articleService.getArticleById(mainId);
		String hql = "from TopicType where pid is null";
		List list = articleDao.getArticleByHql(hql);
		request.setAttribute("article", article);
	    request.setAttribute("list", list);
	    return "/pages/admin/article/addArticle";
	}
	
	@RequestMapping(params = "action=save")
	public String save(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		request.setCharacterEncoding("UTF-8");
		String mainId = request.getParameter("id");
		String articleTpTitle = request.getParameter("articleTpTitle");
		String articleTpicInstr = request.getParameter("articleTpicInstr");
		String adsite_description = request.getParameter("adsite_description");
		String articleTpUrl = request.getParameter("articleTpUrl");
		String typeid = request.getParameter("topicType");
		
		//新增
		if(mainId.length()==0){
	    ArticleTopic article = new ArticleTopic();
	    article.setId(new UUIDGenerator().getUUID());
	    article.setArticleTpTitle(articleTpTitle);
	    article.setArticleTpicInstr(articleTpicInstr);
	    article.setArticleTpUrl(articleTpUrl);
		article.setSys_time(new Date());
		TopicType topicType = topicService.getTopicTypeById(typeid);
		article.setTopicType(topicType);
		articleService.addArticle(article);
		}else{
			    ArticleTopic article = new ArticleTopic();
			    article = articleService.getArticleById(mainId);
			    article.setArticleTpTitle(articleTpTitle);
			    article.setArticleTpicInstr(articleTpicInstr);
			    article.setArticleTpUrl(articleTpUrl);
				article.setSys_time(new Date());
				TopicType topicType = topicService.getTopicTypeById(typeid);
				article.setTopicType(topicType);
				articleService.addArticle(article);
		}
		
		return null;
	}
	
	
	@RequestMapping(params = "action=delete")
	public void delete (HttpServletRequest request, HttpServletResponse response){
		
		try {
			request.setCharacterEncoding("UTF-8");
			String id = request.getParameter("id");
			articleService.delArticle(id);
			response.getWriter().print("true");
		} catch (Exception e) {
			log.error("#####出错了"+e.getMessage());
			
		}
		
	}
	@RequestMapping(params = "action=queryArticle")
	public void queryArticle(HttpServletRequest request, HttpServletResponse response){
		try {
			request.setCharacterEncoding("UTF-8");
			String topicTypeId = request.getParameter("id");
			List<Object[]> result = articleService.getArticleTopicByTopic(topicTypeId);
			response.setContentType("html/txt");
			response.setCharacterEncoding("utf-8");
			response.getWriter().println(getJsonArticle(result));
//			response.getWriter().print("true");
		} catch (Exception e) {
			log.error("#####出错了"+e.getMessage());
			
		}
		
	}
	private String getJsonArticle(List<Object[]> tt){
		StringBuffer sb  = new StringBuffer();
		sb.append("{article:[");
		for(Object[] obj : tt){
			sb.append("{id:\""+obj[0]+"\",name:\""+obj[1]+"\"},");
		}
		if(sb.toString().endsWith(",")){
			
			sb.delete(sb.length()-1, sb.length());
		}
		sb.append("]}");
		return sb.toString();
	}
	/**
	 * @param list
	 * @param pageInfo
	 * @return
	 */
	private String getJsonString(List list, Map pageInfo) {

		List mapList = new ArrayList();   
		for (int i = 0; i < list.size(); i++) {
			ArticleTopic article = (ArticleTopic) list.get(i);
			Map cellMap = new HashMap();
			cellMap.put("numid", i+1);
			cellMap.put("cell", new Object[]{
    				
    				article.getId(),
    				i+1,
    				article.getArticleTpTitle(),
    				article.getArticleTpicInstr(),
    				article.getArticleTpUrl(),
    				article.getTopicType().getType_name(),
    				DateUtils.getDate2Str("yyyy-MM-dd HH:mm",article.getSys_time())
    				
    				});
    		  
    				mapList.add(cellMap);
    				
		}
		
    	pageInfo.put("rows", mapList);
    	com.tueye.ajax.json.JSONObject object = new com.tueye.ajax.json.JSONObject(pageInfo);
    	return object.toString();
	}
	/**
	 * 
	 * @param obj
	 * @return
	 */
	@SuppressWarnings("unused")
	private Object getJsonString(Object obj){
		
		JSONObject json = JSONObject.fromObject(obj);
		//log.info("############# "+json);
		return json;
	}

}
